package cn.guozeyiblog.client;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import javax.security.auth.PrivateCredentialPermission;

import net.youmi.android.banner.AdSize;
import net.youmi.android.banner.AdView;
import crittercism.android.i;
import cn.guozeyiblog.blogutils.ArticleDetail;
import cn.guozeyiblog.client.ArticleDetailActivity.GetArticleDetail;
import cn.guozeyiblog.client.SearchActivity.AsyGetBlogList;
import cn.guozeyiblog.client.XListView.IXListViewListener;
import cn.guozeyiblog.netutils.HttpUtil;
import cn.guozeyiblog.netutils.JsoupUtils;
import cn.guozeyiblog.netutils.NetWorkStatus;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class CateArticleListActivity extends Activity implements IXListViewListener {
	private XListView xlist;
	private ProgressBar pbar;
	private ArrayList<ArticleDetail> alist;
	private ArticleAdapter adapter;
	private static String FLAG_ARTICLE_REFUSH="REFUSH";
	private static String FLAG_ARTICLE_LOAD="LOAD";
	private static String FLAG_ARTICLE_NODATA="NODATA";
	private String blogurl;
	private int pager=1;
	private RelativeLayout adlayout;
	@SuppressLint("NewApi")
	@Override
	
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		alist = new ArrayList<>();
		setContentView(R.layout.article_cateactivity);
		xlist = (XListView) findViewById(R.id.cate_result_list);
		pbar = (ProgressBar) findViewById(R.id.cate_progress);
		adlayout = (RelativeLayout) findViewById(R.id.adLayout);
		//------------------------AD------------------------------
		AdView adView = new AdView(getApplicationContext(), AdSize.FIT_SCREEN);
		if(adlayout!=null){
			adlayout.addView(adView);
		}
		
		pbar.setVisibility(View.VISIBLE);
		//blogurl = getIntent().getExtras().getString("url", "http://guozeyiblog.cn/?sort=4");
		blogurl = getIntent().getStringExtra("url");
		
		xlist.setXListViewListener(this);
		xlist.setPullRefreshEnable(false);
		xlist.setPullLoadEnable(true);
		xlist.setDivider(null);
		adapter = new ArticleAdapter(alist, getApplicationContext());
		xlist.setAdapter(adapter);
		if(NetWorkStatus.isNetworkAvailable(getApplicationContext())){
			new AsyGetBlogList().execute(blogurl,FLAG_ARTICLE_REFUSH);
		}else {
			Toast.makeText(getApplicationContext(), "你的网络不可用哦", 0).show();
		}
		
		xlist.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(getApplicationContext(), ArticleDetailActivity.class);
				intent.putExtra("url", alist.get(position-1).getLink());
				startActivity(intent);
			}
		});
	}
	
	/**
	 * ArticleList异步请求
	 * @author kutear
	 *
	 */
	class AsyGetBlogList extends AsyncTask<String, String, Void>{

		@Override
		protected Void doInBackground(String... params) {
			// TODO Auto-generated method stub
			String result = HttpUtil.httpGet(params[0]);
			ArrayList<ArticleDetail> addlist = JsoupUtils.GetBlogList(result);
			if (addlist.size()>0) {
				//刷新
				if (params[1].equals(FLAG_ARTICLE_REFUSH)) { //判断是通过刷新还是加载得到的数据
					boolean flag = false;   //判断是否加载新数据的标志
					for (int i = addlist.size()-1; i>=0;i--) {
						//判断是否已经存在
						if (!Contains(addlist.get(i))) {
							alist.add(0,addlist.get(i));
							flag = true;
						}
					}
					if (!flag) {  //加载到的数据都是重复的
						publishProgress(FLAG_ARTICLE_NODATA);
					}
					//加载	
				}else {
					boolean flag = false;   //判断是否加载新数据的标志
					for (int i = addlist.size()-1; i>=0;i--) {
						if (!Contains(addlist.get(i))) {
							alist.add(addlist.get(i));
							flag = true;
						}
					}
					if (!flag) {
						publishProgress(FLAG_ARTICLE_NODATA);
					}
				}
			}else {
				publishProgress(FLAG_ARTICLE_NODATA);
			}

			for (ArticleDetail d:alist) {
				System.out.println("articletitle"+d.getTitle());
			}
			publishProgress("");
			return null;
		}

		//判断listarray中是否包含某个对象
		public boolean Contains(ArticleDetail a){
			for (int i = 0; i < alist.size(); i++) {
				if (alist.get(i).getId()==a.getId()) {
					return true;
				}
			}
			return false;
		}


		@Override
		protected void onProgressUpdate(String... values) {
			// TODO Auto-generated method stub
			Log.v(">>>>>>>", "onprogressUpdate");
			if (values[0].equals(FLAG_ARTICLE_NODATA)) {
				Toast.makeText(getApplicationContext(), "no more data", 0).show();
				return ;
			}
			adapter.notifyDataSetChanged();
		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			//停止刷新...setting time
			xlist.stopLoadMore();
			xlist.stopRefresh();
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String time = format.format(new Date());
			xlist.setRefreshTime(time);
			pbar.setVisibility(View.GONE);
		}
	}


	@Override
	public void onRefresh() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onLoadMore() {
		// TODO Auto-generated method stub
		pager++;
		new AsyGetBlogList().execute(blogurl+"&page="+pager,FLAG_ARTICLE_LOAD);
	}
}
